import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { parseIconValue } from './utils';
import styles from './index.module.less';

const Icon = props => {
    const { icon, iconfontClassName, className, size, style: customStyle, ...otherProps } = props;
    let iconName = '';
    let color = '';
    if (icon) {
        if (typeof icon === 'string') {
            const parsedValue = parseIconValue(icon);
            // eslint-disable-next-line prefer-destructuring
            iconName = parsedValue.iconName;
            // eslint-disable-next-line prefer-destructuring
            color = parsedValue.color;
        } else {
            // eslint-disable-next-line prefer-destructuring
            iconName = icon.iconName;
            color = icon.color || '#999';
        }
    }
    const [iconColor, backgroundColor] = color.split('|');
    return (
        <i
            className={classNames([className, iconfontClassName, iconName, styles.icon])}
            style={{
                color: iconColor,
                backgroundColor: backgroundColor || '#eee',
                width: `${size}px`,
                height: `${size}px`,
                lineHeight: `${size}px`,
                fontSize: `${Math.ceil(size * 20 / 32)}px`,
                ...customStyle
            }}
            {...otherProps}
        />
    );
};

Icon.propTypes = {
    // iconfont 类名
    iconfontClassName: PropTypes.string.isRequired,
    // 要显示的图标, 可以是 Object { iconName, color }, 也可是 String 'iconName|前景色|背景色'
    icon: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    // 图标尺寸, 影响宽高和图标的大小
    size: PropTypes.number
};

Icon.defaultProps = {
    icon: null,
    size: 40
};

Icon.displayName = 'Icon';

export default Icon;
